<template>
  <a-card>
    <Header :title="'返回'" :subTitle="$route.params.id == 'null' ?  '创建新的模版': '编辑模版'" :hasBackPath="true" @headerBack="$router.back()"></Header>
    <a-spin :spinning="spinning" size="large">
      <a-row>
        <a-col :span="16">
          <a-form-model
            ref="rulesForm"
            :model="form"
            :rules="rules"
            :labelCol="{ lg: { span: 6 }, sm: { span: 8 } }"
            :wrapperCol="{ lg: { span: 14 }, sm: { span: 17 } }"
          >
            <a-form-model-item label="模版名称" prop="templateName">
              <a-input
                :maxLength="15"
                v-model="form.templateName"
                placeholder="请输入模版名称"
              />
              <div> 注：请把字数控制在15字以内</div>
            </a-form-model-item>
            <a-form-model-item label="背景图片设置" prop="img">
              <JImageUpload :uploadParams="getUploadParams()" :isMultiple="true" :fileSize="1" :number="1" :accept="'image/*'" @fileChange="fileImageChange" v-model="imgList"></JImageUpload>
              <div>注：图片比例限为，支持PNG, JPG和GIF格式，大小不超过1M</div>
            </a-form-model-item>
            <a-form-model-item label="背景色设置" prop="color">
              <a-input style="width: 50%;"  v-model="form.color"  >
                <a-tooltip slot="suffix">
                  <div class="color-box" :style="{background: form.color ? form.color : ''}"></div>
                </a-tooltip>
              </a-input>
            </a-form-model-item>

            <a-form-model-item label="参与规则文字内容配置" required>
              <j-editor :toolbar="toolbar" v-model="form.content" />
<!--              <a-textarea v-model="form.remark" hidden placeholder="请输入" :rows="4" :maxLength="10" />-->
              <!-- <div>注：请把字数控制在x以内</div> -->
            </a-form-model-item>
<!--            <a-form-model-item label="活动规则文字颜色设置" prop="color">-->
<!--              <a-input prefix="#" style="width: 50%;"  v-model="form.color" >-->
<!--                <a-tooltip slot="suffix">-->
<!--                  <div class="color-box" :style="{background: form.color ? '#'+form.color : ''}"></div>-->
<!--                </a-tooltip>-->
<!--              </a-input>-->
<!--            </a-form-model-item>-->
            <a-form-model-item label="券失效是否需要提示" prop="unvalidOn">
              <a-radio-group v-model="form.unvalidOn">
                <a-radio :value="1">
                  是
                </a-radio>
                <a-radio :value="0">
                  否
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
            <!-- <a-form-model-item  class="hidden-title" label="券失效提示" prop="notice">
              <a-textarea allowClear ref="inputArea" @blur="handleInputBlur" v-model="form.notice" placeholder="请输入" :rows="3" :maxLength="maxLength" />
              <a style="text-decoration: underline;" @click="addNum">插入过期券数量</a>
            </a-form-model-item> -->
          </a-form-model>
        </a-col>
        <a-col :span="6">
          <h3>效果预览：</h3>
          <div class="page" :style="{background: form.color ? form.color : ''}">
            <img :src="form.img.url" alt="" class="banner">
            <div class="coupon-box">优惠券</div>
            <div class="text-wrapper">
              <div class="titl">参与规则</div>
              <div v-html="form.content"></div>
            </div>
          </div>
        </a-col>
      </a-row>
      <a-divider />
      <div style="text-align: center">
        <a-button htmlType="submit" type="primary" @click="handleSubmit">确认保存</a-button>
      </div>
    </a-spin>
  </a-card>
</template>
<script>
  import { showPageCreate, showPagDetail, showPageEdit } from '@/api/headquartersCoupon/index'
  import globalData from '@assets/js/common'
  import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
  import JEditor from '@/components/jeecg/JEditor'
  import Header from '@/views/box/components/layouts/Header'
  export default {
    components: {
      JImageUpload,
      JEditor,
      Header
    },
    data() {
      return {
        cursorIndex: 0,
        maxLength: 30,
        toolbar: ['styleselect forecolor| bullist numlist | underline strikethrough'],
        spinning: false,
        imgList: [],
        form: {
          unvalidOn: 0,
          notice: '',
          color: '',
          templateName: '',
          img: {},
          content: ''
        },
        rules: {
          notice: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          templateName: [
            { required: true, message: '请输入', trigger: 'blur' }
          ],
          img: [
            { required: true, message: '请上传', trigger: ['change', 'blur'] }
          ],
          unvalidOn: [
            { required: true, message: '请上传', trigger: 'change' }
          ],
          color: [
            { required: true, message: '请输入', trigger: 'blur' },
            {
              validator: (rule, value, callback) => {
                const reg =  /^[#0-9a-zA-Z]*$/g
                if (reg.test(value)) {
                  callback()
                } else {
                  return callback('请输入正确的格式')
                }
              },
                trigger: 'blur'
            }
          ]
        }
      }
    },
    computed: {
    },
    watch: {
    },
    activated() {
    },
    created() {
      this.getDetails()
    },
    mounted() {
    },
    methods: {
      handleInputBlur(e) {
        this.cursorIndex = e.srcElement.selectionStart;
      },
      addNum() {
        const str = '<n>'
        if (!this.form.notice) {
          this.$set(this.form, 'notice', str)
          this.$refs.inputArea.focus()
          return
        }
        if (this.maxLength - this.form.notice.length >= 3) {
            let s1 = ''
            let s2 = ''
            if (this.form.notice.length < this.cursorIndex) {
              this.form.notice = this.form.notice + str
            } else {
                s1 = this.form.notice.substring(0, this.cursorIndex)
                s2 = this.form.notice.substring(this.cursorIndex, this.form.notice.length)
                this.form.notice = s1 + str + s2
            }
        }
        this.$refs.inputArea.focus()
      },
      // 上传图片
      getUploadParams() {
        return { ...globalData.uploadParams }
      },
      fileImageChange(list) {
        console.log('list', list)
        this.form.img = list.length ? list[0] : ''
      },

      // 保存
      handleSubmit() {
        this.$refs.rulesForm.validate(valid => {
          if (valid) {
            if (!this.form.img) {
              this.$message.info('请上传背景图！')
              return
            }
            if (!this.form.content) {
              this.$message.info('请输入参与规则文字内容！')
              return
            }
            const id = this.$route.params.id
            const submitApi = (id === 'null' || !id) ? showPageCreate : showPageEdit
            const data = {
              id: (id === 'null' || !id) ? 0 : id,
              ...this.form,
              img: this.form.img.url,
              status: 0,
              fontColor: "0"
            }
            this.spinning = true
            submitApi(data).then(res => {
              this.spinning = false
              if (res.code === 200) {
                this.$router.go(-1)
              } else {
                this.$message.error(res.msg || res.message)
              }
            }).catch(err => {
              this.spinning = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },
      
      getDetails() {
        const id = this.$route.params.id
        if (id === 'null' || !id) return
        showPagDetail({id}).then(res => {
          if (res.code === 200) {
            this.form = {
              ...res.data,
              unvalidOn: res.data.unvalidOn == -1 ? 0 : res.data.unvalidOn
            }
            this.imgList = [res.data.img]
          } else {
            this.$message.error(res.msg || res.message)
          }
        }).catch(err => {
          this.spinning = false
        })
      }
    }
  }
</script>
<style scoped>
  .association-list /deep/td{
    padding-bottom: 0 !important;
  }
  .hidden-title  /deep/.ant-form-item-label > label{
    visibility: hidden;
  }
  .color-box{
    width: 14px;
    height: 14px;
    border: 1px solid #e6e6e6;
  }
  .page{
    width: 320px;
    height: 600px;
    overflow: hidden;
    overflow-y: auto;
  }
  .page .banner{
    display: block;
    width: 100%;
  }
  .page .titl{
    line-height: 30px;
    font-weight: bold;
  }
  .page /deep/ p{
    margin-bottom: 0;
  }
  .page .text-wrapper{
    padding: 0 10px 10px;
    word-break: break-word;
    background-color: rgba(255, 255, 255, 0.5);
    border-radius: 10px;
    margin: 0 15px;
  }
  .page .coupon-box{
    margin: 10px 20px;
    border: 1px dashed #999;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .hidden-title /deep/ .ant-form-item-label > label {
    visibility: hidden;
  }
</style>
